<script setup>
import {onMounted, ref, watch} from "vue";
import VIcon from "@/components/icon/VIcon.vue";
import VInputTag from "@/components/form/VInputTag.vue";
import {useRouter} from "vue-router";
import {uploadImage} from "@/api/upload.js";
import {ElMessage} from "element-plus";
import {saveArticle} from "@/api/article.js";
import {getCategoryDropList} from "@/api/category.js";

const $router = useRouter();

const emits = defineEmits(['update:modelValue']);
const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false
  },
  articleInfo: {
    type: Object,
    default: function () {
      return {}
    }
  }
});

const categoryList = ref([]);
const tags = ref([]);
const coverImageUploadRef = ref(null);
const fileList = ref([]);
const visible = ref(props.modelValue);
const article = ref(props.articleInfo);

watch(() => props.modelValue, (newValue) => {
  visible.value = newValue;
  showImage(visible.value);
}, {deep: true});
watch(() => props.articleInfo, (newValue) => {
  article.value = newValue;
}, {deep: true});

onMounted(async () => {
  fileList.value = [];
  await categoryDropList();
});

// 获取文章分类下拉列表
const categoryDropList = async () => {
  await getCategoryDropList().then(res => {
    categoryList.value = res.data;
  }).catch(err => {
    console.log(err);
  });
};

// 回显封面图片
const showImage = (show) => {
  fileList.value = [];
  console.log('===>', article.value.coverImage)
  if (show && article.value?.coverImage) {
    fileList.value.push({
      url: article.value?.coverImage,
      name: 'cover.png',
    });
  }
};
const close = () => {
  visible.value = false;
  emits('update:modelValue', false);
};

const publishArticle = async (status) => {
  if (!article.value.brief) {
    ElMessage.warning('文章简介不能为空');
    return;
  }
  article.value.status = status;
  await saveArticle(article.value).then(async (res) => {
    console.log(res);
    visible.value = false;
    await emits('update:modelValue', false);
    await $router.push({path: '/admin/article'});
  }).catch(err => {
    console.log(err);
  });
};
const handleRemove = () => {
  fileList.value = [];
  article.value.coverImage = '';
};
const httpRequest = async (options) => {
  console.log('文件上传', options)
  // 文件上传
  const form = new FormData();
  form.append('file', options.file);
  await uploadImage(form).then(res => {
    console.log(res)
    article.value.coverImage = res.data;
  });
};
</script>

<template>
  <el-dialog v-model="visible" title="文章设置" draggable :close-on-click-modal="false" width="70%" center
             @close="close">
    <div class="v-article-settings">
      <div class="v-settings-brief">
        <h3>简介</h3>
        <el-input v-model="article.brief" :rows="6" :autosize="{ minRows: 6, maxRows: 6 }"
                  type="textarea" show-word-limit maxlength="255" placeholder="请输入文章简介"/>
      </div>
      <div class="v-settings-bottom">
        <div class="v-cover-image">
          <el-upload ref="coverImageUploadRef" :http-request="httpRequest" action="#" list-type="picture-card"
                     :file-list="fileList" :limit="1">
            <v-icon icon="Plus" size="24"/>
            <template #file="{ file }">
              <div>
                <img class="el-upload-list__item-thumbnail" :src="file.url" alt=""/>
                <span class="el-upload-list__item-actions">
                <span @click="handleRemove">
                  <v-icon icon="Delete" size="22" color="#F56C6C"/>
                </span>
              </span>
              </div>
            </template>
          </el-upload>
        </div>
        <div class="v-article-tags">
          <div>
            <h3>分类：</h3>
            <el-select v-model="article.categoryId" placeholder="请选择文章分类" style="max-width: 240px" clearable>
              <el-option v-for="item in categoryList" :key="item.id" :value="item.id" :label="item.name"/>
            </el-select>
          </div>
          <div>
            <h3>标签：</h3>
            <v-input-tag v-model="tags"/>
          </div>
        </div>
      </div>
    </div>
    <template #footer>
      <div class="dialog-footer">
        <el-button type="warning" @click="close">取消发布</el-button>
        <el-button type="info" @click="publishArticle(0)">保存草稿</el-button>
        <el-button type="success" @click="publishArticle(1)">立即发布</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<style scoped>

/* 重写 element plus 样式 */
:deep(.el-textarea__inner) {
  resize: none;
}

.v-article-settings {
  
  .v-settings-brief {
    padding: 6px 10px;
    box-sizing: border-box;
    background-color: rgba(0, 0, 0, 0.05);
    
    h3 {
      margin-bottom: 10px;
    }
  }
  
  .v-settings-bottom {
    margin-top: 10px;
    background-color: rgba(0, 0, 0, 0.05);
    display: flex;
    flex-direction: row;
    padding: 10px;
  }
  
  .v-cover-image {
    flex: 1;
  }
  
  .v-article-tags {
    margin-left: 10px;
    flex: 2;
    
    > div {
      display: flex;
      align-items: center;
      margin: 0 10px 10px 0;
    }
  }
}

::v-deep(.el-upload--picture-card), ::v-deep(.el-upload-list__item) {
  width: 100px;
  height: 100px;
  line-height: 110px;
  text-align: center;
}
</style>